package com.smart.community.region.controller;

import com.smart.community.commons.result.Result;
import com.smart.community.region.service.IResidentHouseholdService;
import com.smart.community.region.vo.PageResult;
import com.smart.community.region.vo.ResidentHouseholdVO;
import com.smart.community.region.vo.ResidentDetailVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.smart.community.region.service.IResidentService;
import com.smart.community.region.entity.Resident;

/**
 * 住户聚合查询Controller 提供住户管理的综合查询功能
 * 
 * @author Wu.Liang
 * @since 2025-07-28
 */
@RestController
@RequestMapping("/region/residents")
@Tag(name = "住户管理", description = "住户管理相关接口")
@Slf4j
public class ResidentAggregateController {

	@Autowired
	private IResidentHouseholdService residentHouseholdService;
	
	@Autowired
	private IResidentService residentService;
	
    // 延后按需注入
    // @Autowired
    // private IHouseholdService householdService;

	/**
	 * 住户信息统计
	 */
	@GetMapping("/statistics")
	@Operation(summary = "住户信息统计", description = "获取住户相关的统计信息")
	public Result<Map<String, Object>> getResidentStatistics(@RequestParam(required = false) Long householdId) {
		Map<String, Object> statistics = new HashMap<>();

		try {
			if (householdId != null) {
				// 按房户ID统计
				PageResult<ResidentHouseholdVO> result = residentHouseholdService.getResidentList(householdId, 1, Integer.MAX_VALUE);
				List<ResidentHouseholdVO> residents = result.getRecords();
				
				int totalCount = residents.size();
				int ownerCount = (int) residents.stream().filter(r -> r.getResidentType() != null && r.getResidentType() == 1).count();
				int familyCount = (int) residents.stream().filter(r -> r.getResidentType() != null && r.getResidentType() == 2).count();
				int tenantCount = (int) residents.stream().filter(r -> r.getResidentType() != null && r.getResidentType() == 3).count();
				
				statistics.put("totalCount", totalCount);
				statistics.put("ownerCount", ownerCount);
				statistics.put("familyCount", familyCount);
				statistics.put("tenantCount", tenantCount);
			} else {
				// 全局统计
				statistics.put("totalCount", 0);
				statistics.put("ownerCount", 0);
				statistics.put("familyCount", 0);
				statistics.put("tenantCount", 0);
			}
		} catch (Exception e) {
			log.error("获取住户统计信息失败", e);
			statistics.put("totalCount", 0);
			statistics.put("ownerCount", 0);
			statistics.put("familyCount", 0);
			statistics.put("tenantCount", 0);
		}

		return Result.success(statistics);
	}

	/**
	 * 住户搜索
	 * 
	 * @throws Exception
	 */
	@GetMapping("/search")
	@Operation(summary = "住户搜索", description = "根据条件搜索住户信息")
	public Result<List<ResidentHouseholdVO>> searchResidents(@RequestParam(required = false) String keyword,
			@RequestParam(required = false) Long householdId, @RequestParam(required = false) Integer residentType,
			@RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size)
			throws Exception {
		// 这里可以实现复杂的搜索逻辑
		// 根据关键词、房户ID、住户类型等条件进行搜索

		if (householdId != null) {
			PageResult<ResidentHouseholdVO> result = residentHouseholdService.getResidentList(householdId, current,
					size);
			return Result.success(result.getRecords());
		}

		return Result.success();
	}

	/**
	 * 住户详情查询
	 */
	@GetMapping("/detail/{residentId}")
	@Operation(summary = "住户详情查询", description = "查询指定住户的详细信息")
    public Result<ResidentDetailVO> getResidentDetail(@PathVariable Long residentId) {
        ResidentDetailVO detail = new ResidentDetailVO();

        try {
            // 住户基本信息
            Resident resident = residentService.getById(residentId);
            if (resident != null) {
                detail.setId(resident.getId());
                detail.setRealName(resident.getRealName());
                detail.setIdentityType(resident.getIdentityType());
                detail.setIdentityNo(resident.getIdentityNo());
                detail.setGender(resident.getGender());
                detail.setBirthday(resident.getBirthday());
                detail.setPhone(resident.getPhone());
                detail.setEmail(resident.getEmail());
                detail.setEducation(resident.getEducation());
                detail.setProfession(resident.getProfession());
                detail.setWorkUnit(resident.getWorkUnit());
                detail.setNativePlace(resident.getNativePlace());
                detail.setEmergencyContact(resident.getEmergencyContact());
                detail.setEmergencyPhone(resident.getEmergencyPhone());
                detail.setVehicleInfo(resident.getVehicleInfo());
                detail.setPetInfo(resident.getPetInfo());
                detail.setSpecialNeeds(resident.getSpecialNeeds());
                detail.setStatus(resident.getStatus());
                detail.setCreateTime(resident.getCreateTime());
                detail.setUpdateTime(resident.getUpdateTime());
            }

            // 住户关联房户信息
            PageResult<ResidentHouseholdVO> result = residentHouseholdService.getHouseholdList(residentId, 1, Integer.MAX_VALUE);
            List<ResidentHouseholdVO> households = result.getRecords();
            if (!households.isEmpty()) {
                ResidentHouseholdVO rh = households.get(0);
                detail.setResidentType(rh.getResidentType());
                detail.setResidentTypeName(rh.getResidentTypeName());
                detail.setMoveInDate(rh.getMoveInDate());
                detail.setMoveOutDate(rh.getMoveOutDate());
                detail.setContractStartDate(rh.getContractStartDate());
                detail.setContractEndDate(rh.getContractEndDate());
                detail.setMonthlyRent(rh.getMonthlyRent());
                detail.setDeposit(rh.getDeposit());
                detail.setContractNo(rh.getContractNo());
                detail.setApplyStatus(rh.getApplyStatus());
                detail.setApplyStatusName(rh.getApplyStatusName());
                detail.setHouseholdId(rh.getHouseholdId());
                detail.setRemark(rh.getRemark());

                // 从VO中直接带出聚合好的社区/楼栋/单元/房号及ID
                detail.setCommunityId(rh.getCommunityId());
                detail.setCommunityName(rh.getCommunityName());
                detail.setBuildingId(rh.getBuildingId());
                detail.setBuildingName(rh.getBuildingName());
                detail.setUnitId(rh.getUnitId());
                detail.setUnitName(rh.getUnitName());
                detail.setRoomNumber(rh.getRoomNumber());
            }
        } catch (Exception e) {
            log.error("获取住户详情失败，住户ID：{}", residentId, e);
        }

        return Result.success(detail);
    }



	/**
	 * 住户房户列表（带分页）
	 * 
	 * @throws Exception
	 */
	@GetMapping("/resident/{residentId}/households")
	@Operation(summary = "住户房户列表", description = "查询指定住户关联的房户列表，支持分页")
	public Result<PageResult<ResidentHouseholdVO>> getResidentHouseholds(@PathVariable Long residentId,
			@RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size)
			throws Exception {
		PageResult<ResidentHouseholdVO> result = residentHouseholdService.getHouseholdList(residentId, current, size);
		return Result.success(result);
	}
}